-- Thanks: https://github.com/sathishmanohar/quick-buffer-jump
local M = {}

local strings = require('plenary.strings')
local color = require('utils.color')
local t = require('utils.table')
local misc = require('utils.misc')
local futil = require('utils.file')
local fnamemodify = vim.fn.fnamemodify

-- files is an array table of file full path
function M.quick_select(files)
    if #files == 0 then
        require('notify')('No recently files exists!')
        return
    end

    local api = vim.api
    local lines = {}
    local file_map = {}  -- Table to map line numbers to file name
    local highlight_info = {}  -- Store highlight position info
    local alphabet = misc.get_alphabet()
    local alphabet_count = 1
    local alphabet_max = string.len(alphabet)

    -- Create buffer for the floating window
    local float_buf = api.nvim_create_buf(false, true)

    t.foreach(files,function(f)
        if f ~= ''  and alphabet_count < alphabet_max then
            local name = fnamemodify(f, ":.") --shorten fn
            local alphabet_label = alphabet:sub(alphabet_count, alphabet_count)
            local formatted_path, parent_end, parent_end2, parent_end3 = futil.split_file_name_2(name, 67)
            if formatted_path ~= nil then
                local label = alphabet_label .. ' ' .. formatted_path
                t.append(lines, label)

                file_map[#lines] = f
                highlight_info[#lines] = {
                    parent_end = parent_end,
                    parent_end2 = parent_end2,
                    parent_end3 = parent_end3
                }
                -- require('notify')(tostring(parent_end2) .. '+' .. tostring(parent_end3) .. ' ' .. parent)
                -- require('notify')(label)

                -- Map the alphabet key to the fn
                local map_cmd = "<cmd>lua vim.api.nvim_win_close(vim.fn.bufwinid("
                                .. float_buf .. "), true); vim.cmd('e " .. f .. "')<CR>"
                api.nvim_buf_set_keymap(float_buf, 'n', alphabet_label, map_cmd, {noremap = true, silent = true})

                alphabet_count = (alphabet_count % #alphabet) + 1
            end
        end
    end)

    --local max_height = math.max(1, math.min(#lines, math.floor(vim.o.lines * 0.8)))
    local max_height = #lines + 2
    local width = 70
    local row = (vim.o.lines - max_height) / 2
    local col = (vim.o.columns - width) / 2

    -- Create the floating window
    local float_win = api.nvim_open_win(float_buf, true, {
		--title = cwd,
        --title_pos = "right",
        relative = 'editor',
        width = width,
        height = max_height,
        row = row,
        col = col,
        style = 'minimal',
        border = 'single'
    })

    api.nvim_win_set_option(float_win, 'cursorline', false)
    --api.nvim_set_option_value('cursorline', true, {win=float_win})

    -- display title
    local cwd = fnamemodify(vim.fn.getcwd(), ":~")
    local w = strings.strdisplaywidth(cwd)
    local s = string.rep(' ',width-w)
    api.nvim_buf_set_lines(float_buf, 0, -1, true, { s .. cwd })

    -- display content
    api.nvim_buf_set_lines(float_buf, 1, -1, false, lines)

    -- Apply highlights for each alphabet label
    t.foreach(lines,function(_,i)
        local start_pos = 0
        local end_pos = 1
        api.nvim_buf_add_highlight(float_buf, -1, 'AlphabetLabel', i, start_pos, end_pos)

        if highlight_info[i] then  -- i+1 because highlight_info uses 1-based indexing
            local info = highlight_info[i]
            api.nvim_buf_add_highlight(float_buf, -1, 'AlphabetPath', i, 2, info.parent_end+3)
            api.nvim_buf_add_highlight(float_buf, -1, 'AlphabetPath', i, info.parent_end2, info.parent_end2+info.parent_end3+2)
        end
    end)

    -- Store the file map in a buffer-local variable
    api.nvim_buf_set_var(float_buf, "file_map", file_map)

    -- Key mapping for Enter to switch to the file of the current line
    vim.api.nvim_create_user_command('QuickFileSelectorEnter', function()
        local f = vim.api.nvim_buf_get_var(float_buf,'file_map')[vim.api.nvim_win_get_cursor(0)[1]-1]
        if not f then
            return
        end -- title
        vim.api.nvim_win_close(vim.fn.bufwinid(float_buf), true)
        vim.cmd('e ' .. f)
    end, {})

    api.nvim_buf_set_keymap(float_buf, 'n', '<CR>', "<cmd>QuickFileSelectorEnter<CR>", {noremap = true, silent = true})

end

return M
-- EOP
